﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

using Analysis.DAL;
using Analysis.DAL.Repositories;
using Analysis.Entities;
using Analysis.Code;

namespace Analysis
{
    public partial class UserManagement : BaseDataPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!AccessConfirm("Пользователи"))
            {
                throw new HttpException(401, "Доступ закрыт");
            }

            if (!IsPostBack)
            {
                LoadData();
            }
        }

        public override void LoadData()
        {
            using (var repo = RepositoryFactory.ResolveRepository<UserRepository>())
            {
                gridUsers.DataSource = repo.FindAll();
                gridUsers.DataBind();
                upMain.Update();
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            LoadData();
        }

        protected void upUserDetails_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Request["__EVENTTARGET"]))
                if (Request["__EVENTTARGET"] != upUserDetails.ClientID)
                    return;

            if (!string.IsNullOrEmpty(Request["__EVENTARGUMENT"]))
            {
                hdUserId.Text = Request["__EVENTARGUMENT"];

                using (var repo = RepositoryFactory.ResolveRepository<UserRepository>())
                {
                    ddlDepart.DataSource = repo.DepartCombo(false, true);
                    ddlDepart.DataBind();
                }

                if (hdUserId.Text != "-1")
                {
                    using (var userRepo = RepositoryFactory.ResolveRepository<UserRepository>())
                    {
                        lblDialogTitle.Text = "Редактирование пользователя";
                        User usr = userRepo.Find(Convert.ToInt32(hdUserId.Text));
                        txtFirstName.Text = usr.FirstName;
                        txtLastName.Text = usr.LastName;
                        txtEmail.Text = usr.Email;
                        txtPhone.Text = usr.Phone;
                        
                        rbIsFullAccess.Checked = usr.IsFullAccess;
                        rbIsFullAccessNot.Checked = !usr.IsFullAccess;

                        chbIsPageAddress.Checked = usr.IsPageAddress;
                        chbIsPageAssort.Checked = usr.IsPageAssort;
                        chbIsPageMML.Checked = usr.IsPageMML;
                        chbIsPageReport.Checked = usr.IsPageReport;
                        chbIsPageSale.Checked = usr.IsPageSale;
                        chbIsPageSetup.Checked = usr.IsPageSetup;
                        chbIsPageUser.Checked = usr.IsPageUser;

                        ddlDepart.SelectedValue = usr.DepartId.ToString();
                        
                        lnkChangePassword.Visible = true;
                        lnkChangePassword.Attributes.Add("onclick", string.Format("javascript:showPasswordChange({0});", hdUserId.Text));
                    }
                }
                else
                {
                    lblDialogTitle.Text = "Создание пользователя";

                    txtFirstName.Text = "";
                    txtLastName.Text = "";
                    txtEmail.Text = "";
                    txtPhone.Text = "";

                    rbIsFullAccess.Checked = false;
                    rbIsFullAccessNot.Checked = true;

                    chbIsPageAddress.Checked = false;
                    chbIsPageAssort.Checked = false;
                    chbIsPageMML.Checked = false;
                    chbIsPageReport.Checked = false;
                    chbIsPageSale.Checked = false;
                    chbIsPageSetup.Checked = false;
                    chbIsPageUser.Checked = false;

                    ddlDepart.SelectedValue = "-1";

                    lnkChangePassword.Visible = false;
                }
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "ShowEdit", "$('#userDialog').dialog('open');", true);
            }
        }

        protected void gridUsers_RowDataBound(Object Sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                User item = (User)e.Row.DataItem;
                
                ImageButton btn = (ImageButton)e.Row.FindControl("btnDelete");
                btn.Visible = item.CanDelete;
            }
        }

        protected void gridUsers_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gridUsers.PageIndex = e.NewPageIndex;
            LoadData();
        }

        protected void btnSaveUser_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid)
                return;

            if (hdUserId.Text == "-1")
            {
                if (Membership.GetUserNameByEmail(txtEmail.Text) != null)
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "Alert", "alert('Данный email уже используется!');", true);
                    return;
                }
            }

            using (var repo = RepositoryFactory.ResolveRepository<UserRepository>())
            {
                User usr;

                if (hdUserId.Text == "-1")
                {
                    usr = new User();
                    AssignUserValues(usr);

                    string pwd = Guid.NewGuid().ToString().Split(new char[] { '-' })[0];
                    repo.AddManual(usr, pwd);

                    lbldetailDialog.Text = "Пользователь создан";
                    UserNameDetail_text.Text = string.Format("Имя пользователя: {0}", txtEmail.Text);
                    UserPasswordDetail_text.Text = string.Format("Пароль: {0}", pwd);
                    up_UserInformationDetail.Update();
                    //JsCodeToRunOnReady = "$('#userDialog').dialog('close'); $('#detailDialog').dialog('open');";
                    ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "Alert", "$('#userDialog').dialog('close'); $('#detailDialog').dialog('open');", true);
                }
                else
                {
                    usr = repo.Find(Convert.ToInt32(hdUserId.Text));
                    AssignUserValues(usr);

                    string result = repo.Update(usr);
                    if (!string.IsNullOrEmpty(result))
                    {
                        ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "Alert", string.Format("alert('{0}');", result), true);
                        return;
                    }
                    else
                    {
                        ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "Alert", "alert('Информация обновлена!');", true);
                    }
                }
            }

            LoadData();
        }

        void AssignUserValues(User usr)
        {
            usr.LastName = txtLastName.Text;
            usr.FirstName = txtFirstName.Text;
            usr.Email = txtEmail.Text;
            usr.Phone = FormatPhone(txtPhone.Text);

            usr.IsFullAccess = rbIsFullAccess.Checked;

            usr.IsPageAddress = chbIsPageAddress.Checked;
            usr.IsPageAssort = chbIsPageAssort.Checked;
            usr.IsPageMML = chbIsPageMML.Checked;
            usr.IsPageReport = chbIsPageReport.Checked;
            usr.IsPageSale = chbIsPageSale.Checked;
            usr.IsPageSetup = chbIsPageSetup.Checked;
            usr.IsPageUser = chbIsPageUser.Checked;

            usr.DepartId = Convert.ToInt32(ddlDepart.SelectedValue);
            
        }

        protected void btnSavePassword_Click(object sender, EventArgs e)
        {
            using (var repo = RepositoryFactory.ResolveRepository<UserRepository>())
            {
                User usr = repo.Find(Convert.ToInt32(hdUserId1.Value));
                if (usr == null) return;

                MembershipUser u = Membership.GetUser(usr.Email);
                u.ChangePassword(usr.Password, tbPassword.Text);

                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "HideChange", "$('#passwordDialog').dialog('close'); alert('Пароль изменен!');", true);
            }
        }

        protected void Users_Command(object sender, CommandEventArgs e)
        {
            int id = Convert.ToInt32(e.CommandArgument.ToString());

            using (var repo = RepositoryFactory.ResolveRepository<UserRepository>())
            {
                switch (e.CommandName)
                {
                    case "delete":
                        repo.Delete(id);
                        break;
                }
            }
            LoadData();
        }
    }
}